package de.carcophan.jimdb.service.sessionbeans;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.logging.Logger;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import de.carcophan.jimdb.gwt.server.Session;
import de.carcophan.jimdb.gwt.shared.entites.Movie;
import de.carcophan.jimdb.gwt.shared.entites.Tag;
import de.carcophan.jimdb.gwt.shared.entites.User;
import de.carcophan.jimdb.gwt.shared.entites.UserMovies;
import de.carcophan.jimdb.service.QueryController;
import de.carcophan.jimdb.service.json.MovieJson;
import de.carcophan.jimdb.service.json.ToEntity;

/**
 * Session Bean implementation class ServiceSessionBean
 */
@Stateless
@LocalBean
public class ServiceSessionBean {

	Logger logger = Logger.getLogger(ServiceSessionBean.class);

	@PersistenceContext
	private EntityManager em;

	@Inject
	private ToEntity toEntity;

	@Inject
	private QueryController queryController;

	@EJB
	private IsolatedTransactions isolatedTransactions;

	@Inject
	private Session session;

	public ServiceSessionBean() {
	}

	public List<Movie> fromImdbApi(String searchValue) throws Exception {
		logger.debug("ServiceSessionBean.fromImdbApi() " + searchValue);
		List<Movie> movies = queryController.findMoviesByTitleSubstring(
				searchValue, 5);

		if (movies.size() < 5) {
			logger.debug("ServiceSessionBean.fromImdbApi() found "
					+ movies.size() + " in DB, querying IMDB");
			BufferedReader in = null;
			try {
				String urlstring = "http://imdbapi.org/?title="
						+ searchValue
						+ "&type=json&plot=simple&episode=1&limit=5&yg=0&mt=none&lang=en-US&offset=&aka=simple&release=simple";
				URL url = new URL(urlstring);
				URLConnection connection = url.openConnection();
				in = new BufferedReader(new InputStreamReader(
						connection.getInputStream()));

				Gson gson = new Gson();
				JsonParser parser = new JsonParser();
				JsonArray asJsonArray = parser.parse(in).getAsJsonArray();
				movies = new ArrayList<Movie>();

				for (JsonElement jsonElement : asJsonArray) {
					MovieJson movieJson = gson.fromJson(jsonElement,
							MovieJson.class);
					Movie movie = toEntity.toMovie(movieJson);
					movies.add(movie);

				}

				for (Movie movie : movies) {
					if (queryController.findMovieByJimdbId(movie.getImdbId()) == null) {
						System.out.println("persisting ---- "
								+ movie.getTitle());
						try {
							isolatedTransactions.persist(movie);
						} catch (Exception e) {
							logger.error(e);
						}
					}
				}

			} catch (IllegalStateException e) {
				logger.info(e.getMessage());
			} finally {
				try {
					in.close();
				} catch (Exception e) {
					// dont want to handle anything here
				}
			}
		}
		return movies;
	}

	public void addTag(String tag, String hexColor) {
		Tag tagBean = queryController.findTagByName(tag);
		if (tagBean == null) {
			tagBean = new Tag();
			tagBean.setName(tag);
		}
		tagBean.setHexColor(hexColor);
		em.merge(tagBean);
	}

	public void saveTag(String imdbId, String selectedTag) {
		List<UserMovies> userMovies = queryController.findUserMovie(imdbId,
				session.getUser().getId());
		Tag tag = queryController.findTagByName(selectedTag);
		if (userMovies != null && !userMovies.isEmpty()) {
			UserMovies userMovie = userMovies.get(0);
			userMovie.setTag(tag);
		} else {
			UserMovies userMovie = new UserMovies();
			userMovie.setTag(tag);
			userMovie.setMovie(queryController.findMovieByJimdbId(imdbId));
			userMovie.setUser(em.find(User.class, session.getUser().getId()));
			em.persist(userMovie);
		}
	}

}
